<template>
  <div class="login-container">
        <div class="main-box">
        <el-form>
          <div class="title-tips">运维技术中心机器学习平台</div>
    </el-form>
      <el-form  class="login-form" :model="ruleForm" status-icon :rules="rules" ref="loginForm" style="width: 350px;margin-left: 64%">
              <div class="login_header_title">
                <a class="title1" rel="external nofollow" @click="loginWay = true" :class="{ active: loginWay === true }">
                  <span>短信登录</span>
                </a>
                <a class="title2" rel="external nofollow" @click="loginWay = false" :class="{ active: loginWay === false }">
                  <span>谷歌登录</span>
                </a>
              </div>
            <el-form-item prop="username">
              <el-input :prefix-icon="Avatar" style="width: 300px; height: 40px; margin-top: -10px; margin-bottom: -2px;" placeholder="账号" v-model.number="ruleForm.username" clearable></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input :prefix-icon="Lock" style="width: 300px; height: 40px; margin-top: 0px; margin-bottom: -2px;" placeholder="请输入密码" v-model="ruleForm.password" show-password clearable></el-input>
            </el-form-item>
        <div :class="{ on: !loginWay }">
            <el-form-item prop="verificationCode">
              <el-input style="width: 250px; height: 40px; margin-top: 0px; margin-bottom: -2px;" v-model="ruleForm.verificationCode" placeholder="请输入短信验证码" clearable></el-input>
              <el-button style="position: relative; height: 40px; right: -1px; margin-top: 0px; margin-bottom: -2px; width: 50px;" color="#722ed1" :disabled="disableSendButton || isCountingDown" :class="{ 'get_verfication': true, 'is-disabled': disableSendButton || isCountingDown }" @click.prevent="handleSendVerificationCode">{{ sendButtonText }}</el-button>
            </el-form-item>
        </div>
        <div :class="{ on: loginWay }">
        <el-form-item prop="otpCode">
          <el-input style="width: 300px; height: 40px; margin-top: 0px; margin-bottom: -2px;" placeholder="Google Authenticator 验证码" type="text" maxlength="8" v-model="ruleForm.otpCode" clearable></el-input>
        </el-form-item>
        <a class="title3" href="http://127.0.0.1:8088/ge_registration" rel="external nofollow">
            <img src="../../assets/cy.png" alt="谷歌登录" style="width: 15px; height: 15px;" />
            <el-link href="http://127.0.0.1:8088/ge_registration" type="info" style="position: relative; top: -3px; right: -2px;">注册或重置口令</el-link>
        </a>
       </div>
          <el-form-item>
              <el-button style="position: relative; right: -50px; margin-top: 10px; width: 200px;" color="#722ed1" @click="submitForm()">提交</el-button>
          </el-form-item>
      </el-form>
      </div>
  </div>
</template>

<script>

import { Avatar, Lock} from "@element-plus/icons-vue";

/* eslint-disable */
export default {
  data () {
    var checkUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    var checkotpCode = (rule, value, callback) => {
      if (value === '' && !this.loginWay) {
        callback(new Error('请输入谷歌验证'))
      } else {
        callback()
      }
    }
    var validatePassWord = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    var checkverificationCode = (rule, value, callback) => {
      if (value === '' && this.loginWay) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      loginWay: true,
      Avatar,
      Lock,
      error: null,
      disableSendButton: false,
      sendButtonText: '发送',
      isCountingDown: false,
      countDownSeconds: 60,
      ruleForm: {
        username: '',
        password: '',
        otpCode: "",
        verificationCode: "",
      },
      rules: {
        username: [
          { validator: checkUserName, trigger: 'blur' }
        ],
        otpCode: [
          { validator: checkotpCode, trigger: 'blur' }
        ],
        verificationCode: [
          { validator: checkverificationCode, trigger: 'blur' }
        ],
        password: [
          { validator: validatePassWord, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    async handleSendVerificationCode() {
      if (this.isCountingDown) {
        return;
      }
      // 禁用按钮并更改按钮文本和样式
      this.disableSendButton = true;
      this.sendButtonText = `${this.countDownSeconds}s`;
      this.isCountingDown = true;
      const timer = setInterval(() => {
        if (this.countDownSeconds > 0) {
          this.countDownSeconds--;
          this.sendButtonText = `${this.countDownSeconds}s`;
        } else {
          clearInterval(timer);
          this.disableSendButton = false;
          this.sendButtonText = '发送';
          this.isCountingDown = false;
          this.countDownSeconds = 60;
        }
      }, 1000);
      // 发送请求获取验证码
      await this.$http.post("/send_verification_code/", {
        username: this.ruleForm.username,
        password: this.ruleForm.password
      })
          .then(response => {
            const message = response.data.message
            if(response.status === 200){
              this.$message.success(message);
            }
            if(response.status === 201){
              this.$message.error(message);
            }
          })
          .catch(error => {
            console.error(error);
            this.$message.error('');
            clearInterval(timer);
            this.disableSendButton = false;
            this.sendButtonText = '发送';
            this.isCountingDown = false;
            this.countDownSeconds = 60;
          });
    },
    async submitForm() {
      let data
      if (this.loginWay) {
        data = {
          username: this.ruleForm.username,
          password: this.ruleForm.password,
          verificationCode: this.ruleForm.verificationCode,
          otp_code: "0",
        }
      } else {
        data = {
          username: this.ruleForm.username,
          password: this.ruleForm.password,
          otp_code: this.ruleForm.otpCode,
          verificationCode: "0",
        }
      }
      // console.log(data)
      await this.$refs.loginForm.validate(async valid => {
        if (!valid) return;//校验没通过，返回
        await this.$http.post('/add_and_bind_google_auth1/', data)
            .then(response => {
              const permission = response.data.permission
              const login = response.data.login
              if (response.status === 200) {
                if (login) {
                  localStorage.setItem("account", response.data.token);
                  localStorage.setItem("permission", permission);
                  localStorage.setItem("login", login);
                  localStorage.setItem("cardid", response.data.cardid);
                  const menus = response.data.menus;
                  localStorage.setItem('menus',JSON.stringify(menus));
                  localStorage.setItem('firstpath', 'true')//登录时路由进行初始化
                  this.$router.push('/home');
                  this.$message.success('登录成功！');
                } else {
                  this.$message.error('当前状态禁止登陆，请联系管理员！');
                }
              } else {
                this.$message.error(response.data.message);
              }
            })
            .catch(error => {
              this.$message.error('访问出现问题，请稍后再试！');
              console.error(error);
            });
      })
    },
  }
}
</script>
<style scoped>
.is-disabled {
  background-color: #ccc;
  color: #999;
}
body{
  margin: 0 auto;
}
.on {
  display: none;
}
.login-container {
  /*font-weight: bold; !* 加粗字体 *!*/
  position: relative; /* 设置为相对定位 */
  z-index: 1;
  width: 100%;
  height: 100%;
  background: url('../../assets/login_images/background.jpg') center center fixed
  no-repeat;
  background-size: cover;

}
.login_header_title a:hover {
  cursor: pointer;
  color: #007aff; /*或者其他喜欢的文本颜色*/
}
.main-box {
  position: fixed;
  top: 50%;
  right: 14%;
  transform: translateY(-50%);
  width: 420px;
  min-width: 100px;
  min-height: 100px;
  height: 520px;
  padding: -40px;
  background-color: white;
  border: 1px solid rgba(221, 221, 221, 0.5); /* 设置边框颜色并添加透明度 */
  box-shadow: 0 3px 8px rgba(221, 221, 221, 0.2); /* 更改阴影颜色并添加透明度 */
  border-radius: 20px; /* 增加圆角 */
  overflow: hidden;
}
.title-tips {
  font-weight: bold; /* 加粗字体 */
  position: absolute;
  top: calc(15%); /* 向上移动 60px */
  right: calc(15%); /* 向右移动 60px */
  font-size: 25px; /* 缩小字体大小 */
  color: #333; /* 更改字体颜色 */
  text-overflow: ellipsis;
  white-space: nowrap;
}
.login-form {
  position: absolute;
  max-width: 100%;
  top: 35%; /* 将元素垂直居中 */
  left: -50%; /* 将元素水平居中 */
}
.login_header_title {
  margin-bottom: 20px;
  /*display: flex;*/
  justify-content: center;
  align-items: center;
}
.title1,
.title2
{
  font-size: 14px; /* 调整字体大小 */
  /*display: inline-block;*/
  margin-right: 10px; /* 添加右侧间距 */
}
.title3 {
  display: inline-block;
  transform: translateX(90px); /* 将元素向左移动 50px */
}
/* 普通状态 */
.login_header_title a {
  color: #999; /* 默认灰色 */
}

/* 激活状态 */
.login_header_title a.active {
  color: #000; /* 变更为黑色 */
  /*font-weight: bold; !* 加粗字体 *!*/
  font-size: 18px; /* 放大字体 */
}
p {
  color: #ddd; /* 将元素颜色设置为浅色 */
  text-indent: 97px;
  position: relative; /* 设置相对定位 */
  font-size: 10px; /* 放大字体 */
}
p:before {
  left: 0;
  margin-left: 18px; /* 负值等于文本的缩进长度 */
}

p:after {
  right: 0;
  margin-right: 22px; /* 负值等于文本的缩进长度 */
}
</style>






